import asyncio
import websockets

connected = set()

# 1. 函数名修改为不与后面的变量冲突（例如改为 websocket_handler）
async def websocket_handler(websocket):
    """处理每个客户端连接的函数"""
    connected.add(websocket)
    #print(f"新客户端连接，当前连接数：{len(connected)}")
    
    try:
        async for message in websocket:
            #print(f"收到消息：{message[:50]}...（长度：{len(message)}）")
            # 广播给其他客户端
            for conn in connected:
                if conn != websocket:
                    await conn.send(message)
                    
    except websockets.exceptions.ConnectionClosed:
        print("客户端断开连接")
    finally:
        connected.remove(websocket)
        #print(f"客户端断开，当前连接数：{len(connected)}")

async def main():
    """启动服务器的主函数"""
    # 2. 这里的变量名改为 server_instance，避免与函数名冲突
    async with websockets.serve(websocket_handler, "127.0.0.1", 5678) as server_instance:
        print(f"服务器已启动，监听 ws://127.0.0.1:5678")
        await server_instance.wait_closed()  # 保持服务器运行

if __name__ == "__main__":
    try:
        asyncio.run(main())  # 现代Python推荐的事件循环启动方式
    except KeyboardInterrupt:
        print("\n服务器已手动关闭")